package com.nero.service.impl;

import com.nero.bean.PO.TbUser;
import com.nero.bean.PO.TbUserExample;
import com.nero.common.pojo.TaotaoResult;
import com.nero.common.utils.JedisClientSingle;
import com.nero.common.utils.SerializeUtils;
import com.nero.dao.TbUserMapper;
import com.nero.service.IUserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import static com.nero.common.utils.JedisClientSingle.SESSION_EXPIRE;
import static com.nero.common.utils.JedisClientSingle.USER_INFO;

/**
 * Created by Nero on 18/8/6.
 */
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    TbUserMapper tbUserMapper;
    @Resource
    JedisClientSingle jedisClientSingle;
    private Logger logger = LogManager.getLogger(this.getClass());

    public TaotaoResult Login(TbUser tbUser) throws IOException {
        TbUser form = tbUser;
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria c = example.createCriteria();
        c.andUsernameEqualTo(form.getUsername());
//        c.andPasswordEqualTo(form.getPassword());
        List<TbUser> found = tbUserMapper.selectByExample(example);
        if (found.size() == 0) return TaotaoResult.build(400, "用户名或密码错误"); // 用户名错误
        TbUser user = found.get(0);
        String formPassword = user.getPassword();
        String userPassword = DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes());
        logger.info("formPassword :" + formPassword + "userPassword :" + userPassword);
        if (formPassword.equals(userPassword)) {
            System.out.println("登录成功");
            String token = UUID.randomUUID().toString();
            user.setPassword(null);
            jedisClientSingle.set(USER_INFO + ":" + token, SerializeUtils.serialize(user));
            jedisClientSingle.expire(USER_INFO + ":" + token, SESSION_EXPIRE);
            return TaotaoResult.ok(token);
        }
        System.out.println("登录失败");
        return TaotaoResult.build(400, "用户名或密码错误");
    }
}
